<template>
  <el-card class="booking-create-container">
    <h2>会议室预约</h2>

    <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
      <el-form-item label="会议室" prop="roomId">
        <el-select
            v-model="form.roomId"
            placeholder="请选择会议室"
            @change="handleRoomChange"
        >
          <el-option
              v-for="room in availableRooms"
              :key="room.id"
              :label="room.name"
              :value="room.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="预约日期" prop="date">
        <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="选择日期"
            :disabled-date="disabledDate"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <!-- 修改点：拆分时间段为开始时间和结束时间两个独立表单项 -->
      <el-form-item label="开始时间" prop="startTime">
        <el-time-picker
            v-model="form.startTime"
            placeholder="开始时间"
            format="HH:mm"
            value-format="HH:mm"
            :disabled="!form.date"
            :disabled-hours="disabledHoursForStart"
            :disabled-minutes="disabledMinutesForStart"
            :clearable="false"
        />
      </el-form-item>

      <el-form-item label="结束时间" prop="endTime">
        <el-time-picker
            v-model="form.endTime"
            placeholder="结束时间"
            format="HH:mm"
            value-format="HH:mm"
            :disabled="!form.startTime"
            :disabled-hours="disabledHoursForEnd"
            :disabled-minutes="disabledMinutesForEnd"
            :clearable="false"
        />
      </el-form-item>

      <el-form-item label="用途" prop="purpose">
        <el-input
            v-model="form.purpose"
            type="textarea"
            placeholder="请输入会议或活动用途"
            :rows="3"
        />
      </el-form-item>

      <el-form-item label="参与人数" prop="participants">
        <el-input-number
            v-model="form.participants"
            :min="1"
            :max="selectedRoom ? selectedRoom.capacity : 50"
        />
        <span class="capacity-hint" v-if="selectedRoom">
          最大容量: {{ selectedRoom.capacity }}人
        </span>
      </el-form-item>

      <el-form-item label="指派给他人">
        <el-switch v-model="form.assignToOther" />
        <el-select
            v-if="form.assignToOther"
            v-model="form.assigneeId"
            placeholder="选择指派成员"
            style="margin-left: 10px; width: 200px"
        >
          <el-option
              v-for="user in assignableUsers"
              :key="user.id"
              :label="user.name"
              :value="user.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">提交预约</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="booking-tips">
      <h3>预约须知：</h3>
      <ul>
        <li>请至少提前1小时预约会议室</li>
        <li>单次预约时长不得超过4小时</li>
        <li>预约成功后请按时使用，无故缺席3次将被加入黑名单</li>
        <li>如需修改或取消预约，请在会议开始前2小时操作</li>
      </ul>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserInfoStore } from '../../stores/userInfo'

interface Room {
  id: number
  garden: string
  buildNum: string
  roomNum: string
  capacity: number
  status: boolean
  name: string
}

interface User {
  id: number
  name: string
}

const userInfoStore = useUserInfoStore()

// 表单数据
const form = reactive({
  roomId: null as number | null,
  date: '',
  startTime: '',
  endTime: '',
  purpose: '',
  participants: 1,
  assignToOther: false,
  assigneeId: null as number | null
})

// 表单验证规则 - 修改点：添加时间范围验证
const rules = {
  roomId: [{ required: true, message: '请选择会议室', trigger: 'change' }],
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (!value) {
          callback(new Error('请选择开始时间'))
          return
        }

        // 如果是今天，检查是否提前1小时
        if (form.date === new Date().toISOString().split('T')[0]) {
          const now = new Date()
          const selectedTime = new Date(`${form.date} ${value}`)
          const diffHours = (selectedTime.getTime() - now.getTime()) / (1000 * 60 * 60)

          if (diffHours < 1) {
            callback(new Error('请至少提前1小时预约'))
            return
          }
        }
        callback()
      },
      trigger: 'change'
    }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (!form.startTime) {
          callback(new Error('请先选择开始时间'))
          return
        }

        const start = new Date(`1970-01-01 ${form.startTime}`)
        const end = new Date(`1970-01-01 ${value}`)

        if (end <= start) {
          callback(new Error('结束时间必须晚于开始时间'))
          return
        }

        const durationHours = (end - start) / (1000 * 60 * 60)
        if (durationHours > 4) {
          callback(new Error('单次预约时长不得超过4小时'))
          return
        }

        callback()
      },
      trigger: 'change'
    }
  ],
  purpose: [{ required: true, message: '请输入用途', trigger: 'blur' }],
  participants: [
    { required: true, message: '请输入参与人数', trigger: 'blur' },
    {
      validator: (rule: any, value: number, callback: any) => {
        if (value < 1) {
          callback(new Error('参与人数至少1人'))
        } else if (selectedRoom.value && value > selectedRoom.value.capacity) {
          callback(new Error(`参与人数不能超过会议室容量(${selectedRoom.value.capacity}人)`))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

const formRef = ref()
const availableRooms = ref<Room[]>([])
const assignableUsers = ref<User[]>([
  { id: 1001, name: '张三' },
  { id: 1002, name: '李四' },
  { id: 1003, name: '王五' }
])

// 加载可用会议室
const loadAvailableRooms = async () => {
  try {
    // 生成30个统一命名的会议室
    const mockRooms: Room[] = [];
    const buildings = ['30', '25', '18', '22', '15', '10', '5'];
    const capacities = [10, 30, 50, 150, 300];

    for (let i = 0; i < 30; i++) {
      const buildingIndex = i % 7;
      const garden = `${String.fromCharCode(65 + buildingIndex)}区`; // A-G区
      const roomNum = (100 + i).toString();

      mockRooms.push({
        id: i + 1,
        garden: garden,
        buildNum: buildings[buildingIndex],
        roomNum: roomNum,
        capacity: capacities[Math.floor(Math.random() * capacities.length)],
        status: true,
        name: `${garden}${buildings[buildingIndex]}号楼${roomNum}` // 统一命名格式
      });
    }

    availableRooms.value = mockRooms;
  } catch (error) {
    ElMessage.error('加载会议室失败');
  }
}

// 时间限制 - 修改点：添加时间选择限制
const minStartHour = 8 // 8:00
const maxStartHour = 20 // 20:00
const minEndHour = 8 // 8:00
const maxEndHour = 22 // 22:00

// 禁止选择今天之前的日期
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

// 当前选中的会议室
const selectedRoom = computed(() => {
  if (!form.roomId) return null
  return availableRooms.value.find(r => r.id === form.roomId) || null
})

// 处理会议室选择
const handleRoomChange = (roomId: number) => {
  const room = availableRooms.value.find(r => r.id === roomId)
  if (room && form.participants > room.capacity) {
    form.participants = room.capacity
  }
}

// 修改点：添加时间选择限制函数
const disabledHoursForStart = () => {
  const hours = []
  for (let i = 0; i < minStartHour; i++) hours.push(i)
  for (let i = maxStartHour + 1; i < 24; i++) hours.push(i)
  return hours
}

const disabledMinutesForStart = (selectedHour: number) => {
  if (form.date === new Date().toISOString().split('T')[0] && selectedHour === new Date().getHours()) {
    const minutes = []
    const currentMinute = new Date().getMinutes()
    for (let i = 0; i <= currentMinute; i++) minutes.push(i)
    return minutes
  }
  return []
}

const disabledHoursForEnd = () => {
  const hours = []
  for (let i = 0; i < minEndHour; i++) hours.push(i)
  for (let i = maxEndHour + 1; i < 24; i++) hours.push(i)
  return hours
}

const disabledMinutesForEnd = (selectedHour: number) => {
  if (!form.startTime) return []

  const [startHour, startMinute] = form.startTime.split(':').map(Number)

  if (selectedHour === startHour) {
    const minutes = []
    for (let i = 0; i <= startMinute; i++) minutes.push(i)
    return minutes
  }

  return []
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    // 模拟API调用
    const bookingData = {
      ...form,
      userId: userInfoStore.userInfo.id,
      userName: userInfoStore.userInfo.username,
      room: selectedRoom.value
          ? `${selectedRoom.value.garden} ${selectedRoom.value.buildNum}号楼 ${selectedRoom.value.roomNum}`
          : ''
    }

    console.log('提交预约:', bookingData)

    ElMessageBox.confirm(
        `确认预约 ${bookingData.room} (${form.date} ${form.startTime}-${form.endTime})?`,
        '确认预约',
        { confirmButtonText: '确认', cancelButtonText: '取消' }
    ).then(() => {
      ElMessage.success('预约申请已提交，等待管理员审核')
      resetForm()
    })
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
  form.participants = 1
  form.assignToOther = false
  form.assigneeId = null
}

onMounted(() => {
  loadAvailableRooms()
})
</script>

<style scoped lang="scss">
.booking-create-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;

  h2 {
    text-align: center;
    margin-bottom: 30px;
    color: #333;
  }

  .capacity-hint {
    margin-left: 10px;
    color: #666;
    font-size: 14px;
  }

  .booking-tips {
    margin-top: 30px;
    padding: 15px;
    background-color: #f8f8f8;
    border-radius: 4px;

    h3 {
      margin-top: 0;
      color: #333;
    }

    ul {
      padding-left: 20px;
      color: #666;

      li {
        margin-bottom: 8px;
      }
    }
  }
}
</style>